package com.liuqi.loggers.core.appender;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件输出日志
 *
 * @author liuqi
 * @date 2024/6/5 19:02
 **/
public class FileAppender extends OutputStreamAppender {

    /**
     * 日志文件输出路径
     */
    private String filepath;

    /**
     * 日志输出文件
     */
    private File activeFile;

    @Override
    public void start() {
        openFile();
        super.start();
    }

    public void openFile() {
        this.activeFile = new File(filepath);
        if (!this.activeFile.exists()) {
            this.activeFile.getParentFile().mkdirs();
            try {
                activeFile.createNewFile();
            } catch (IOException e) {
                throw new IllegalArgumentException("logger write file[" + this.activeFile.getPath() + "] not permission by write");
            }
        }
        if (!this.activeFile.canWrite()) {
            throw new IllegalArgumentException("logger write file[" + this.activeFile.getPath() + "] not permission by write");
        }
        try {
            setOutputStream(new FileOutputStream(this.activeFile, true));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public void setFilepath(String filepath) {
        this.filepath = filepath;
    }

    public String getFilepath() {
        return filepath;
    }

    public File getActiveFile() {
        return activeFile;
    }
}
